#!/bin/bash

FUNC=(
"get_conns_conns"
"get_slave_status"
"get_ceph_status"
"get_unknown_conns"
)
MYSQL_USER='zbx'
export MYSQL_PWD='ZBX_fpb@))9'
WHITE_PORT_FILE='
white_port.list
custom_port.list
'
WHITE_IP_FILE='
white_ip.list
custom_ip.list
'

function get_conns_count {
    local sum=0
    links=$(ss -anp${1:0:1}|awk '{print $4}'|grep '^10\.[0-9]\+\.[0-9]\+\.[0-9]\+:')
    shift
    for port in ${@:?}; do
        res=$(echo "$links"|grep ":$port$"|wc -l)
        let sum="$sum + $res"
    done
    echo $sum
}

function get_slave_status {
    local slave_status=$(mysql -u$MYSQL_USER -e 'show slave status\G')
    [[ "$slave_status" =~ Slave_IO_Running:\ Yes.*Slave_SQL_Running:\ Yes ]] && \
        echo "$slave_status"|grep 'Seconds_Behind_Master:'|grep -o '[0-9]\+' && \
        return
    echo -e "$slave_status"
}

function get_ceph_status {
    ceph -s
}

function get_unknown_conns {
    local conns=$(ss -anpHtu|awk '$5~/^[1-9]/ && $6~/^[1-9]/{print $0}')
    for port in $(cat $WHITE_PORT_FILE 2>/dev/null | sort | uniq); do
        conns=$(echo -e "$conns"|awk '$5!~/':$port$'/{print $0}')
    done
    for ip in $(cat $WHITE_IP_FILE 2>/dev/null | sort | uniq); do
        conns=$(echo -e "$conns"|awk '$6!~/'^$ip:'/{print $0}')
    done
    echo -ne "$conns"
}

# main
cd $(dirname $0)
if [[ "$1" =~ ^[0-9]+$ ]] && [ 0 -le $1 -a ${#FUNC[@]} -gt $1 ]; then
    cmd=${FUNC[$1]}
    shift
    $cmd $@
else
    echo 'Wrong arguments!'
fi

